# -*- coding: utf-8 -*-
'''Game main module.

Contains the entry point used by the run_game.py script.

Feel free to put all your game code here, or in other modules in this "gamelib"
package.
'''

import pyglet
from pyglet.gl import *
from pyglet.window import key

import player
import house
import enemy
import music
import bullets
import menu
from constants import *
from objects import World
import isometric
import camera
import intro

def draw_box(rect):
    verts = [rect[0],rect[3], #topleft
             rect[1],rect[3], #topright
             rect[1],rect[2],
             rect[0],rect[2],]
    pyglet.graphics.draw(4, GL_QUADS,
        ('v2i', verts) )

class Game(pyglet.event.EventDispatcher):
    def __init__(self, window):
        super(Game, self).__init__()
        self.parent = window

        grass = pyglet.resource.image("grass.png")
        self.grass = pyglet.image.TileableTexture.create_for_image(grass)
        #street = pyglet.resource.image("street.png")
        #self.street = pyglet.image.TileableTexture.create_for_image(street)
        self.level = 1

    def load_level(self):
        levelname = "map"+str(self.level)+".map"
        self.map = isometric.Map(levelname)
        self.cam = camera.Camera(self.map.focus_tile, scale=250)
        World.clear()
        for thingy in self.map.enemies:
            x,y = isometric.isometric_map_coord_to_world_coord(thingy[1], thingy[2])
            World.enemies.append(enemy.enemy_types[thingy[0]](x,y))
        for thingy in self.map.buildings:
            x,y = isometric.isometric_map_coord_to_world_coord(thingy[1], thingy[2])
            World.buildings.append(house.house_types[thingy[0]](x,y))

    def run(self):
        self.load_level()
        daman = player.Bengt(400, 50)
        World.player=daman
        music.play_background("hubbe.ogg")
        pyglet.clock.schedule_interval(self.update, 1.0/FPS)
        self.parent.push_handlers(self)

    def on_draw(self):
        glClear(GL_COLOR_BUFFER_BIT)
        x = (self.parent.width/2.0-self.cam.x)%self.parent.width - self.parent.width
        y = (self.parent.height/2.0-self.cam.y)%self.parent.height - self.parent.height
        self.grass.blit_tiled(x,y,0,640*3, 480*3)
        self.cam.focus(self.parent.width, self.parent.height)
        
        #self.map.draw(self.cam, self.parent.width, self.parent.height)
        house.batch.draw()
        enemy.batch.draw()
        World.player.draw()
        bullets.batch.draw()
    
        self.cam.hud_mode(self.parent.width, self.parent.height)
        World.player.draw_life(self.parent.width/6,0,2*self.parent.width/3)

        return pyglet.event.EVENT_HANDLED

    def on_key_press(self, symbol, modifier):
        if symbol == key.LEFT:
            World.player.start_movin_left()
        if symbol == key.RIGHT:
            World.player.start_movin_right()
        if symbol == key.UP:
            World.player.start_movin_up()
        if symbol == key.DOWN:
            World.player.start_movin_down()
        if symbol == key.SPACE:
            World.player.start_shootin()
        if symbol == key.ESCAPE:
            self.quit()
        if symbol == key.MINUS:
            self.cam.scale *= 2
        if symbol == key.PLUS:
            self.cam.scale /= 2
        return pyglet.event.EVENT_HANDLED

    def on_key_release(self, symbol, modifier):
        if symbol == key.LEFT:
            World.player.stop_movin_left()
        if symbol == key.RIGHT:
            World.player.stop_movin_right()
        if symbol == key.UP:
            World.player.stop_movin_up()
        if symbol == key.DOWN:
            World.player.stop_movin_down() 
        if symbol == key.SPACE:
            World.player.stop_shootin()
        return pyglet.event.EVENT_HANDLED

    def update(self, dt):
        for building in World.buildings:
            building.update(dt)
        for enemy in World.enemies:
            enemy.update(dt)
        World.player.update(dt)
        self.cam.x, self.cam.y = World.player.sprite.position
        for bullet in World.player_bullets:
            bullet.update(dt)
        for bullet in World.enemy_bullets:
            bullet.update(dt)
        self._did_i_win()

    def quit(self):
        self.parent.remove_handlers(self)
        music.stop()
        pyglet.clock.unschedule(self.update)

    def __del__(self):
        self.quit()

    def _did_i_win(self):
        if not World.buildings:
            try:
                #icredibly uggly hack
                self.level += 1
                self.quit()
                self.run()
            except:
                print "I think you won! Congratulations!"
                pyglet.app.exit()
        elif World.player.is_dead:
            self.quit()
            self.run()

def main():
    window = pyglet.window.Window()
    m = menu.Menu(window, window.width/2, window.height/2, ["Run", "Intro", "Toggle Music On/Off","Toggle SFX On/Off","Quit"])
    cammy = camera.Camera((window.width/2, window.height/2),scale=200)
    back = pyglet.resource.image("titlescreeen.png")
    back.anchor_x = back.width/2
    back.anchor_y = back.height
    @m.event
    def on_select(selection):
        if selection == "Run":
            g = Game(window)
            g.run()
        elif selection == "Intro":
            i = intro.Intro(window)
        elif selection == "Toggle Music On/Off":
            music.can_has_music = not music.can_has_music
        elif selection == "Toggle SFX On/Off":
            music.can_has_sfx = not music.can_has_sfx
        else:
            pyglet.app.exit()
    @window.event
    def on_draw():
        window.clear()
        cammy.focus(window.width, window.height)
        back.blit(window.width/2,window.height)
        m.draw()
    
    pyglet.app.run()

